#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<unistd.h>

int ticket=100;

void* Ca_can(void* arg)
{
  //定义互斥锁
  pthread_mutex_t *mutex=(pthread_mutex_t*)arg;

  //线程入口函数
  while(1){
    //抢票之前先进行加锁操作
    pthread_mutex_lock(mutex);
    usleep(10);

    if(ticket>0)
    {
      printf("%p 抢到了 %d 号票！\n",pthread_self(),ticket);
      ticket--;
      //抢票结束之后进行解锁
      pthread_mutex_unlock(mutex);
    }
    else{
      printf("票已经没有了!\n");
      pthread_mutex_unlock(mutex);   //进行解锁
      pthread_exit(NULL); //退出线程
    }
  }
  usleep(1);
  return NULL;
}

int main()
{
  //创建一个线程  
  // int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  // void *(*start_routine) (void *), void *arg);

  pthread_t tid[4];  //用于接收线程 ID,定义四个线程
  const char* arg = "nihaoa";   //传递给入口函数的参数信息

  //定义互斥锁
  pthread_mutex_t mutex;
  //初始化互斥锁
 // int pthread_mutex_init(pthread_mutex_t *restrict mutex,
    //          const pthread_mutexattr_t *restrict attr);
  pthread_mutex_init(&mutex,NULL);
    

  int i=0;
  for(;i<4;++i){
    int ret=pthread_create(&tid[i],NULL,Ca_can,&mutex);
    if(ret!=0){
      perror("pthread_create error!\n");
      return -1;
    }
  }


  //线程等待
  for(i=0;i<4;++i){
    pthread_join(tid[i],NULL);
  }

  //线程运行结束，释放锁
  pthread_mutex_destroy(&mutex);

  return 0;
}
